/*
 * Copyright (C) 2008 Peter Kling
 * 
 * This file is part of 'A Kind of Billiard', a graphical billiard simulation.
 * 
 * 'A Kind of Billiard' is free software: you can redistribute it and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * 'A Kind of Billiard' is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with 'A Kind of Billiard'. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package de.akob.modeling;

import javax.media.opengl.GL;

import de.akob.mathematics.MathVector;

/**
 * Data structure for vertices of a model.
 */
public class Vertex extends MathVector {
	private MathVector normal = null;
	
	/**
	 * Constructs a three dimensional vertex from the given values.
	 * 
	 * @param values varargs/array used to generate vertex
	 * @throws IllegalArgumentException if number of values does not match three
	 */
	public Vertex(double... values) {
		super(values);
		if (values.length != 3)
			throw new IllegalArgumentException("vertex needs exactly 3 components for construction");
	}
	
	/**
	 * Draws the vertex normal (if present).
	 * 
	 * @param gl OpenGL object used for drawing
	 * @param length length the normal is drawn with
	 */
	public void drawNormal(GL gl, double length) {
		if (normal == null)
			return;
		gl.glPushMatrix();
		gl.glTranslated(get(1), get(2), get(3));
		gl.glBegin(GL.GL_LINES);
		gl.glVertex3d(0., 0., 0.);
		gl.glVertex3d(normal.get(1) * length, normal.get(2) * length, normal.get(3) * length);
		gl.glEnd();
		gl.glPopMatrix();
	}
	
	/**
	 * Returns the normal of this vertex.
	 * 
	 * @return vertex normal (null if not present)
	 */
	public MathVector getNormal() {
		return normal;
	}
	
	/**
	 * Executes the OpenGL operations corresponding to this primitive. Needs to be enclosed in proper
	 * <code>glBegin</code> and <code>glEnd</code> calls.
	 * 
	 * @param gl OpenGL object used for drawing
	 * @param useNormal whether to use the vertex normal (if present)
	 */
	public void glEvaluate(GL gl, boolean useNormal) {
		if (normal != null && useNormal)
			gl.glNormal3dv(normal.getElements(), 0);
		gl.glVertex3dv(getElements(), 0);
	}
	
	/**
	 * Sets the normal of this vertex. Note that the given vector will be normalized.
	 * 
	 * @param normal the vertex normal
	 */
	public void setNormal(MathVector normal) {
		normal.normalize();
		this.normal = normal;
	}
}
